package org.blackcat.core.aop;

import org.blackcat.common.StringUtils;
import org.blackcat.core.annotation.IsNull;
import org.blackcat.core.annotation.IsNullOrEmpty;
import org.blackcat.core.annotation.Length;
import org.blackcat.core.annotation.Size;

import java.lang.reflect.Field;

/**
 * Created by Duo Duo on 2017/1/9.
 */
public class AnnotationSolve {

    /**
     * 判断长度大小
     * @param field
     * @param arg
     * @return
     */
    public static final boolean notLength(Field field,Object arg) throws IllegalArgumentException, IllegalAccessException{
        Length length = field.getDeclaredAnnotation(Length.class);
        if(length != null){
            int valueLen = field.getInt(arg);
            if(valueLen < length.min() || valueLen > length.max()){
                return true;
            }
        }
        return false;
    }
    /**
     * 处理对象非空验证
     * @param field
     * @param arg
     * @return
     */
    public static final boolean isNull(Field field,Object arg) throws IllegalArgumentException, IllegalAccessException{
        if(field.getDeclaredAnnotation(IsNull.class) != null){
            if(field.get(arg) == null){
                return true;
            }
        }
        return false;
    }
    /**
     * 处理字符串非空验证
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static final boolean isNullOrEmpty(Field field,Object arg) throws IllegalArgumentException, IllegalAccessException{
        if(field.getDeclaredAnnotation(IsNullOrEmpty.class) != null){
            if(StringUtils.isNullOrEmpty(field.get(arg).toString())){
                return true;
            }
        }
        return false;
    }
    /**
     * 处理大小验证
     * @param field
     * @param arg
     * @return
     */
    public static final boolean notSize(Field field,Object arg) throws IllegalAccessException {
        Size size = field.getDeclaredAnnotation(Size.class);
        if(size != null){
            int value = field.getInt(arg);
            if(value < size.min() || value > size.max()){
                return true;
            }
        }
        return false;
    }
}
